﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Web;
using WebShop.Contracts;
using WebShop.DAL.Interfaces;

namespace WebShop.DAL.Repositories
{
    public class ProductsCartRepository : IProductsCartRepository
    {
        internal const string TempDataCookieKey = "__ControllerProductsCart";

        public ProductsCart LoadCart(HttpContextBase httpContext)
        {
            HttpCookie cookie = httpContext.Request.Cookies[TempDataCookieKey];
            if (cookie != null && !string.IsNullOrEmpty(cookie.Value))
            {
                ProductsCart deserializedTempData = DeserializeTempData(cookie.Value);

                return deserializedTempData;
            }

            return new ProductsCart();
        }

        public ProductsCart LoadCart(ICollection<Order_Detail> orderDet)
        {
            ProductsCart cart = new ProductsCart();

            foreach (var product in orderDet)
            {
                cart.AddProduct(new ProductInCart(product.ProductID, product.Quantity));
            }

            return cart;
        }

        public void SaveCart(HttpContextBase httpContext, ProductsCart cart)
        {
            bool isDirty = (cart != null && cart.Count > 0);

            string cookieValue = SerializeToBase64EncodedString(cart);
            var cookie = new HttpCookie(TempDataCookieKey);
            cookie.HttpOnly = true;

            // Remove cookie
            if (!isDirty)
            {
                cookie.Expires = DateTime.Now.AddDays(-4.0);
                cookie.Value = string.Empty;

                httpContext.Response.Cookies.Set(cookie);

                return;

            }
            cookie.Value = cookieValue;

            httpContext.Response.Cookies.Add(cookie);
        }

        ProductsCart DeserializeTempData(string base64EncodedSerializedTempData)
        {
            byte[] bytes = Convert.FromBase64String(base64EncodedSerializedTempData);
            var memStream = new MemoryStream(bytes);
            var binFormatter = new BinaryFormatter();
            return binFormatter.Deserialize(memStream, null) as ProductsCart /*TempDataDictionary : This returns NULL*/;
        }

        string SerializeToBase64EncodedString(ProductsCart values)
        {
            MemoryStream memStream = new MemoryStream();
            memStream.Seek(0, SeekOrigin.Begin);
            var binFormatter = new BinaryFormatter();
            binFormatter.Serialize(memStream, values);
            memStream.Seek(0, SeekOrigin.Begin);
            byte[] bytes = memStream.ToArray();
            return Convert.ToBase64String(bytes);
        }
    }
}